package com.example.store.service.impl;

import com.example.store.entity.User;
import com.example.store.mapper.UserMapper;
import com.example.store.service.IUserService;
import com.example.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

//用户模块业务层实现类
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        String username = user.getUsername();
        User result = userMapper.findbyUsername(username);
        if(result!=null){
            throw new UsernameDuplicatedException("用户名已经被占用");
        }
        //密码加密处理过程:md5算法实现
        //串+password+串--》交给md5算法加密 连续加载三次
        //串一般称为盐值（本身也是随机的字符串）即 盐值+password+盐值
        String oldPassword = user.getPassword();
        //获取盐值（随机生成一个盐值）
        String salt = UUID.randomUUID().toString().toUpperCase();
        //不全数据： 保存盐值
        user.setSalt(salt);
        //密码加密（MD5）并保存
        String password=getMD5Password(oldPassword,salt);
        user.setPassword(password);
        // 补全数据，代表用户不删除处于正常状态，创建者与修改者及其发生时间应该由业务层解决
        user.setIsDelete(0);
        // 补全数据：日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        Integer rows = userMapper.insert(user);
        if(rows!=1){
            throw new InsertException("注册过程中发生了未知的错误");
        }
    }

    @Override
    public User login(String username, String password) {
        User result = userMapper.findbyUsername(username);
        if(result==null){
            throw new UserNotFoundException("用户不存在");
        }
        //获取数据库密码
        String oldPassword = result.getPassword();
        //获取盐值
        String slat = result.getSalt();
        //传过来的新密码进行md5加密后是否与数据库密码相同
        String newPassword = getMD5Password(password,slat);
        if(!oldPassword.equals(newPassword)){
            throw new PasswordNotMatchException("用户密码错误，请重新输入");
        }
        //判断isDelete的值是否为1，进行逻辑删除判断
        if(result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        //数据筛选，减少传输量，提升系统性能
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(username);
        user.setAvatar(result.getAvatar());
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.fingByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        //原始密码与新密码比较
        oldPassword = getMD5Password(oldPassword, result.getSalt());
        if(!oldPassword.equals(result.getPassword())){
            throw new PasswordNotMatchException("密码错误");
        }
        //新密码加密
        newPassword=getMD5Password(newPassword,result.getSalt());
        Integer rows = userMapper.updataPasswordByUid(uid, newPassword, username, new Date());
        //错误规划
        if(rows!=1){
            throw new UpdataException("修改密码过程中发生未知错误");
        }
    }

    @Override
    public User getdataByUid(Integer uid) {
         User result = userMapper.fingByUid(uid);
         if(result==null || result.getIsDelete()==1){
             throw new UserNotFoundException(" 用户不存在");
         }
         User user = new User();
         user.setGender(result.getGender());
         user.setPhone(result.getPhone());
         user.setEmail(result.getEmail());
         user.setUsername(result.getUsername());
         return user;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.fingByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException(" 用户不存在");
        }
        user.setUid(uid);
        user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if(rows!=1){
            throw new UpdataException("更新数据时异常");
        }

    }


    @Override
    public void changeAvatarByUid(Integer uid, String avatar, String username) {
        User result = userMapper.fingByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException(" 用户不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if(rows!=1){
            throw new UpdataException("更新头像发生未知 异常");
        }
    }

    /** 定义一个md5算法加密过程 */
    public String getMD5Password(String password,String salt ){
        for(int i =0;i<3;i++){
            //md5加密算法
            password=DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        return password;
    }

}
